/**
 * UI管理器类
 * 负责处理所有用户界面交互和事件管理
 */
class UIManager {
    /**
     * 构造函数
     * @param {MapManager} mapManager - 地图管理器实例
     */
    constructor(mapManager) {
        this.mapManager = mapManager;
        this.instructions = document.getElementById('instructions');
        this.loading = document.getElementById('loading');
        this.navTypeContainer = document.getElementById('navTypeContainer');
        this.overlay = document.getElementById('overlay');
        this.drivingBtn = document.getElementById('drivingBtn');
        this.walkingBtn = document.getElementById('walkingBtn');
        
        // 添加下拉菜单相关元素
        this.floorSelect = document.getElementById('floor-select');
        this.roomSelect = document.getElementById('room-select');
        this.navigateBtn = document.getElementById('navigate-btn');
        this.commandOutput = document.getElementById('command-output');
        
        // 教室数据
        this.roomsData = {
            '0': ['01x', '02x', '03x', '04x', '05x', 'st1', 'st2', 'st3', 'st4', 'st5', 'st6'],
            '1': ['101', '10x', '105', '106', '107'],
            '2': ['201', '203', '206', '207', '208', '211', '215', '216', '217'],
            '3': ['301', '303', '306', '307', '308', '311', '312', '314', '315', '316', '318', '31x', '320'],
            '4': ['401', '403', '406', '407', '408', '411', '412', '414', '415', '416', '418', '419', '421', '422', '425', '426', '433', '434', '437', '442', '443'],
            '5': ['501', '502', '503', '506', '507', '509', '510', '511', '513', '514', '516', '517', '520', '521', '50x', '528', '529', '532', '537', '538'],
            '6': ['601', '602', '603', '605', '606', '608', '609', '612', '613', '60x'],
            '7': ['701', '703', '706', '707']
        };
        
        this.isRequesting = false; // 添加请求锁
        this.dropdownsInitialized = false; // 新增：初始化标志

        this.initializeEventListeners();
        this.initializeDropdowns();
    }

    /**
     * 初始化所有事件监听器
     * 包括位置选择、导航类型切换和楼梯口选择等
     */
    initializeEventListeners() {
        document.getElementById('knowLocation').addEventListener('click', () => {
            this.hideInstructions();
            this.mapManager.locationSelected = true;
            this.showNavTypeContainer();
        });
        
        document.getElementById('needLocation').addEventListener('click', () => {
            this.showLoading();
            
            this.mapManager.geolocation.getCurrentPosition((status, result) => {
                this.hideLoading();
                
                if (status === 'complete') {
                    const position = [result.position.lng, result.position.lat];
                    this.mapManager.createTempMarker(position);
                    const nearestEnd = this.mapManager.findNearestEnd(position);
                    this.mapManager.planRoute(position, '当前位置', nearestEnd);
                    
                    this.hideInstructions();
                    this.mapManager.locationSelected = true;
                    this.showNavTypeContainer();
                } else {
                    alert('定位失败，请手动点击地图选择位置');
                }
            });
        });
        
        this.drivingBtn.addEventListener('click', () => {
            this.mapManager.setNavigationType('driving');
            this.walkingBtn.classList.remove('active');
            this.drivingBtn.classList.add('active');
        });
        
        this.walkingBtn.addEventListener('click', () => {
            this.mapManager.setNavigationType('walking');
            this.walkingBtn.classList.add('active');
            this.drivingBtn.classList.remove('active');
        });
        
        // 添加楼梯口选择下拉菜单
        this.stairSelect = document.getElementById('stair-select');
        
        // 添加楼梯口选择事件
        this.stairSelect.addEventListener('change', () => {
            const selectedStairId = this.stairSelect.value;
            // 查找对应的楼梯口终点
            const selectedEndPoint = MAP_CONFIG.endPoints.find(point => point.stairId === selectedStairId);
            
            if (selectedEndPoint) {
                // 移动地图到选中的楼梯口位置
                this.mapManager.map.setCenter(selectedEndPoint.position);
                // 创建临时标记
                this.mapManager.createTempMarker(selectedEndPoint.position);
                
                // 更新地图终点
                window.currentEnd = selectedEndPoint;
                
                // 如果有当前位置，则规划路线
                if (window.currentStart) {
                    this.mapManager.planRoute(
                        window.currentStart, 
                        window.currentStartName || '当前位置', 
                        selectedEndPoint
                    );
                }
                
                // 显示选中的楼梯口信息
                this.appendToOutput(`已选择楼梯口: ${selectedEndPoint.name}\n位置: 经度 ${selectedEndPoint.position[0]}, 纬度 ${selectedEndPoint.position[1]}\n\n`);
            }
        });
    }

    /**
     * 初始化下拉菜单和相关事件
     * 处理楼层选择和教室选择的联动
     */
    initializeDropdowns() {
        if (this.dropdownsInitialized) return;
        // 标记为已初始化
        this.dropdownsInitialized = true;

        // 初始化楼层选项
        // 楼层选择变化时更新教室选项
        this.floorSelect.addEventListener('change', () => {
            const selectedFloor = this.floorSelect.value;
            
            // 清空教室选择
            this.roomSelect.innerHTML = '<option value="">选择教室</option>';
            
            if (selectedFloor !== '') {
                // 启用教室选择
                this.roomSelect.disabled = false;
                
                // 添加对应楼层的教室
                const rooms = this.roomsData[selectedFloor] || [];
                rooms.forEach(room => {
                    const option = document.createElement('option');
                    option.value = room;
                    option.textContent = room;
                    this.roomSelect.appendChild(option);
                });
            } else {
                // 如果未选择楼层，禁用教室选择
                this.roomSelect.disabled = true;
            }
        });
        
        // 导航按钮点击事件
        this.handleNavigateClick = async () => {
            if (this.isRequesting) return; // 如果正在请求中，直接返回
            this.isRequesting = true; // 设置请求锁
            const selectedRoom = this.roomSelect.value;
            const selectedStair = document.getElementById('stair-select').value || 'st1';
            
            if (!selectedRoom) {
                alert('请先选择教室');
                return;
            }
            
            try {
                
                
                // 清空之前的输出
                this.commandOutput.textContent = '';
                
                // 显示导航信息
                this.appendToOutput(`正在规划从 ${selectedStair} 到 ${selectedRoom} 的路线...\n\n`);
                
                // 发送导航请求到服务器
                const response = await fetch('/api/find_route', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        start: selectedStair,
                        end: selectedRoom
                    })
                });
                
                const data = await response.json();
                
                if (data.error) {
                    this.appendToOutput(`错误: ${data.error}\n`);
                    return;
                }
                
                // 只显示导航指令
                if (data.instructions && data.instructions.length > 0) {
                    this.appendToOutput(`楼内导航指令:\n`);
                    data.instructions.forEach((instruction, index) => {
                        this.appendToOutput(`${index + 1}. ${instruction}\n`);
                    });
                }
            } catch (error) {
                this.appendToOutput(`请求错误: ${error.message}\n`);
            } finally {
                this.isRequesting = false; // 请求完成，释放锁
            }
        };
        
        // 移除旧的事件监听器并添加新的
        this.navigateBtn.removeEventListener('click', this.handleNavigateClick);
        this.navigateBtn.addEventListener('click', this.handleNavigateClick);
    }
    
    /**
     * 向输出区域添加文本
     * @param {string} text - 要添加的文本内容
     */
    appendToOutput(text) {
        if (this.commandOutput) {
            this.commandOutput.textContent += text;
            // 自动滚动到底部
            this.commandOutput.scrollTop = this.commandOutput.scrollHeight;
        }
    }

    /**
     * 隐藏初始指引界面
     */
    hideInstructions() {
        this.instructions.style.display = 'none';
        this.overlay.style.display = 'none';
    }
    
    /**
     * 显示加载提示
     */
    showLoading() {
        this.loading.style.display = 'block';
    }
    
    /**
     * 隐藏加载提示
     */
    hideLoading() {
        this.loading.style.display = 'none';
    }
    
    /**
     * 显示导航类型选择容器
     */
    showNavTypeContainer() {
        this.navTypeContainer.style.display = 'block';
    }
    
    /**
     * 根据终点更新楼梯口选择
     * @param {Object} endPoint - 终点信息对象
     */
    updateStairSelect(endPoint) {
        if (this.stairSelect && endPoint && endPoint.stairId) {
            this.stairSelect.value = endPoint.stairId;
        }
    }
}

/**
 * 页面加载完成后初始化UI和地图
 */
document.addEventListener('DOMContentLoaded', function() {
    // 声明全局变量便于调试
    window.mapManager = new MapManager();
    window.uiManager = new UIManager(window.mapManager);
    
    // 初始化地图
    mapManager.initializeMap();
});